/*
* 客人查询插件
*/

;(function($){
	
	$.fn.ho_guest_gledger_search = function(options){
		var el = this;
		var opts = {
			condition:"",//获取数据源条件json
			where : {1:1},
			multiSelect : false, //是否多选
			dataBack : function(){},
			oper : "ledger",
			closeBack : function(){},
			dataBackRoom:function(){},
			returnRoom:"no",
			gno:0,
			arg:"",//功能分类('转账','在住')('转账路径','预定在住')('取消')('NOSHOW','预定未抵')('离店')空字符串代表全部客人
			together:"",//是否只查询同行客人YES/NO
			includeme:"NO",//是否包含自身YES/NO
			
		};
		var param = $.extend(opts,options);
		var guestList = new GuestList(el,param);
	};
	
	var GuestList = function(el,param){
		this.el = el;
		this.param = param;
		this.initHtml();
		this.initGrid();
		this.bindEvent();
		this.el.find("#filterSearch").val(this.param.gname);
		this.el.find("#btnFilterSearch").trigger("click");
	}
	
	GuestList.prototype = {
		
		bindEvent : function(){
			
			var el = this.el;
			var param = this.param;
			var t = this;
			
			//是否同行客人
			el.find("#together").bind("click",function(){
				if($(this).is(":checked")) 
					$(this).attr("value","YES");
				else
					$(this).attr("value","");
				el.find("#btnFilterSearch").trigger("click");
			});
			
			this.el.find("#btnFilterSearch").click($.proxy(function(){
				var filVal = this.el.find("#filterSearch").val();
				
				//获取查询条件
//				{"where":{"all_search":""},"arg":{"arg":"","gno":"","together":"","includeme":""}}
				var $this=this;
				var paramter={};
				paramter.where={"all_search":filVal};
				paramter.arg={"arg":param.arg,"gno":param.gno,"together":el.find("#together").attr("value"),"includeme":param.includeme};
				$.ajax({
					type : 'POST',
					async:true, 
					url : $.HSAPI_AJAXURL+"/qms/mobile/procedure2",
					data : $.HSAPI_ASKJSONINFO(JSON.stringify(paramter),'HoWSASCGuestSelect','{}'),
					dataType : 'json',  
					success : function(data){
			            if(data.RETURN == 1){
			            	$this.freshJqgrid(data.WS);
			            }else{
			            	jf_alert(data.MSG);
						}
					},  
					error : function(data){ 
						jf_alert('HoWSASCGuestSelect错误提示:系统后台提交错!' + JSON.stringify(data))
					}  
				})
			},this))
			
			this.el.find("#filterSearch").keydown($.proxy(function(e){
				if(e.keyCode==13){
					this.el.find("#btnFilterSearch").trigger("click");
				}
			},this));
			
			this.el.find("#serviceModalSelect").click($.proxy(function(){
				var data = null;
				if(this.param.multiSelect){
					data = this.el.find("#gridTableGuestGledger").jqGrid("getGridParam","selarrrow")
				}else{
					var rowid = this.el.find("#gridTableGuestGledger").jqGrid("getGridParam","selrow")
					data = $("#gridTableGuestGledger").jqGrid("getRowData",rowid)
				}
				this.param.dataBack(data);
				var roomDate = ""
				var arr = []	
				if(this.param.multiSelect){
					var ids=this.el.find("#gridTableGuestGledger").jqGrid('getGridParam','selarrrow');
					$.each(ids,function(key,value){
						var rowData = $("#gridTableGuestGledger").jqGrid('getRowData',value);
						arr.push(rowData.room)
					})
					roomDate = arr.join(',');
				}else{
					var rowid = $("#gridTableGuestGledger").jqGrid("getGridParam","selrow")
					var rowData = $("#gridTableGuestGledger").jqGrid("getRowData",rowid)
					roomDate = rowData.room
				}	
				this.param.dataBackRoom(roomDate);
			},this));
			
			this.el.find("#btnModalBack,#close-dialog").click(function(){
				el.modal("hide");
				el.empty();
				param.closeBack();
			});
		},
		
		initHtml : function(){
			var param = this.param;
			
			//创建模态窗体
			this.el.addClass("modal").attr("tabindex","-2").attr("data-backdrop","static");
			html='<div class="modal-dialog" style="min-width:800px;">'+
	    			'<div class="modal-content">'+
			  			'<div class="modal-header no-padding">'+
							'<div class="table-header">'+
								'<span id="modal-h4">'+$.i18n.propJsp("选择客人")+'</span>'+
							'</div>'+
						'</div>'+
			  			'<div class="modal-body">'+
			  				'<div class="well well-sm">'+
				  				'<div class="clearfix">'+
					  				'<span class="pull-left">'+
										'<input class="input-xlarge" id="filterSearch" type="text" placeholder="'+$.i18n.propJsp("房号/姓名")+'"/>&nbsp;&nbsp;'+
										'<span class="btn-group" style="margin-top:-5px;">'+
											'<button id="btnFilterSearch" class="btn btn-sm btn-info">'+
												'<i class="ace-icon fa fa-search"></i>'+
												$.i18n.propJsp("查询")+
											'</button>';
//											if(param.gno!=0){
//											html+='<label style="margin-top:6px;margin-left:5px;">'+
//													'<input value="YES" id="together" name="together" type="checkbox" class="ace" checked>'+
//													'<span class="lbl smaller-90"><font color="#a94442" size="2">'+$.i18n.propJsp("同行客人")+'</font></span>'+
//												'</label>';
//											}
									html+='</span>'+
									'</span>'+
									'<span class="pull-right">'+
										'<span class="btn-group">'+
											'<button class="btn btn-info btn-sm " id="serviceModalSelect" data-dismiss="modal">'+
					    				 		'<i class="ace-icon fa fa-check"></i>'+$.i18n.propJsp("选择")+
											'</button>'+
											'<button class="btn btn-default btn-sm" id="btnModalBack" data-dismiss="modal">'+
												'<i class="ace-icon fa fa-undo"></i>'+$.i18n.propJsp("返回")+
										    '</button>'+
										'</span>'+
									'</span>'+
				  				'</div>'+
			  				'</div>'+
			  				'<div class="widget-box">'+
			  					'<div id="gridWidthGuestGledger" class="widget-body">'+
			  						'<table id="gridTableGuestGledger"></table>'+
			  						'<div id="gridPagerGuestGledger_pager"></div>'+
			  					'</div>'+
			  				'</div>'+
						'</div>'+
	    			'</div>'+
	    		'</div>';
			this.el.html(html);
		},
		
		initGrid : function(){
			var el = this.el;
			var param = this.param;
			this.el.find("#gridTableGuestGledger").jqGrid('GridUnload')
			
			var wherestring = {wherestring:["@@WS",""]};
			var multiSelect = this.param.multiSelect
			//jqgrid初始化函数
			jf_initJqgrid(
				{		
					height:"300",//表格高度
					width:766,//表格宽度
					url:$.HSAPI_AJAXURL+"/qms/mobile/procedure2",
					wherestring : wherestring,
					where : {"1":"1"},
					multiSelect : multiSelect, //是否多选
					pager_selector : "#"+el.find("#gridPagerGuestGledger_pager").attr("id"),
					oper:"jqGridCre"
				},el.find("#gridTableGuestGledger"),el,param
			)
		},
		freshJqgrid : function(wherestring){
			wherestring += this.param.condition;
			var el = this.el;
//			el.find("#gridPagerGuestGledger_pager").empty();
//			alert(el.find("#gridPagerGuestGledger_pager").attr("id"))
			var where = this.param.where;
			jf_initJqgrid(
				{		
					url:$.HSAPI_AJAXURL+"/qms/mobile/procedure2",
					wherestring : {wherestring:["@@WS",wherestring]},
					where : where,
					pager_selector : "#"+el.find("#gridPagerGuestGledger_pager").attr("id"),
					oper:"jqGridFre"
				},this.el.find("#gridTableGuestGledger")
			)
		}
	};
	
	//jqgrid初始化函数
	var jf_initJqgrid = function(options,$this,el,param){
		//获取jquery对象
		var grid_selector = $this;
		
//		$(grid_selector).jqGrid('GridUnload'); 
		
		//默认参数
		var init = {
				oper:"",
				pager_selector:"",
				height:"",
				width:"",
				url:"",
				where:{},
				multiSelect : false, //是否多选
				wherestring:{},	 
				fileds:{"fileds":["gname","room","arr_d","exp_dep_d","rooms","fname",
				                  "gno","pno","status","agent_id","comp_id","group_id",
				                  "rmtype","adults","child","rcode","rate","nights",
				                  "party","statuscn","acc_name1","acc_name2","acc_name3","acc_name4",
				                  "rmlinks","balance","grno","sortby"
				                  ]},
				table:{"table":{"table":"viewJqGrid_ho_guest_listAll"}}
		};
		
		//初始化参数
		var initDate = $.extend(init, options);
		//执行操作
		switch(initDate.oper){
			case 'jqGridCre':jqGridCre(initDate,grid_selector,el,param);							 						
							 break;
			case 'jqGridFre':jqGridFre(initDate,grid_selector,el,param);							 
							 break;
		};
	}
	
	/*
	 * 私有函数
	 * 初始化jqgrid
	 */
	function jqGridCre(initDate,grid_selector,el,param){	
		
		//表格位置 initDate.width.width()
		$(window).on("resize.jqGrid", function() { 
//			alert("jqgrid窗口大小改变")
			grid_selector.jqGrid("setGridWidth", initDate.width);
		})  		
		var parent_column = grid_selector.closest("[class*='col-']");
		$(document).on("settings.ace.jqGrid", function(ev, event_name, collapsed) {
//			alert("重新设置jqgrid")
			if (event_name === "sidebar_collapsed" || event_name === "main_container_fixed") {
				setTimeout(function() {
					grid_selector.jqGrid("setGridWidth", initDate.width);
				},0);
			}
		});
		var initc=jQuery.extend({}, initDate.where,initDate.fileds,initDate.table,initDate.wherestring);
		//构造表格
//		console.log(initDate.url);
		jQuery(grid_selector).jqGrid({
			subGrid : false,
			url : initDate.url,
			datatype : "json",
			postData : $.HSAPI_ASKJSONINFO( JSON.stringify(initc),'RetrieveJqGridList',"{}",'listWithPage'),
			height : initDate.height,
			colNames : ["房号","房型","提示","姓名","客人状态",
			            "#","抵店","离店","余额",
			            "PNO","GNO","GRNO","PARTY"],
			colModel : [{
				name : "room",//"房号",
				index : "room",
				width : 50,
			},{
				name : "rmtype",//"房型",
				index : "rmtype",
				width : 60,
			},{
				name : "rmlinks",//"提示",
				index : "rmlinks",
				width : 80,
			},{
				name : "gname",//"姓名",
				index : "gname",
				width: 80,
			},{
				name : "statuscn",//"客人状态",
				index : "statuscn",
				width: 85, 
				hidden : false,
            	formatter:function(cellvalue, options, rowObject){
            		var str = ""
            		if(cellvalue=="预定取消"){
            			str = 	'<span class="label label-inverse">'+
            						'<s>'+cellvalue+'</s>'+
            					'</span>';
            		}else if(cellvalue=="预定"){
            			str = 	'<span class="label label-success arrowed-in-right arrowed-in">'+
            						'<i class="ace-icon fa fa-exclamation-triangle bigger-120"></i>'+
            						cellvalue+
            					'</span>';
            		}else if(cellvalue=="入住"){
            			str = 	'<span class="label label-info arrowed arrowed-right">'+
        							cellvalue+
            						'<i class="ace-icon fa fa-exclamation-triangle bigger-120"></i>'+
            					'</span>';
            		}else if(cellvalue=="散客抵店"){
            			str = 	'<span class="label label-info arrowed arrowed-right">'+
            						cellvalue+
            						'<i class="ace-icon fa fa-exclamation-triangle bigger-120"></i>'+
            					'</span>';
            		}else if(cellvalue=="停留"){
            			str = 	'<span class="label label-info arrowed-right">'+
            						cellvalue+
            						'<i class="ace-icon fa fa-exclamation-triangle bigger-120"></i>'+
            					'</span>';
            		}else if(cellvalue=="离店"){
            			str = 	'<span class="label label-pink arrowed-right">'+
            						cellvalue+
            					'</span>';
            		}else if(cellvalue=="预离店"){
            			str = 	'<span class="label label-info arrowed-right">'+
            						cellvalue+'<i class="ace-icon fa fa-exclamation-triangle bigger-120"></i>'+
            					'</span>';
            		}
            		
            		return str;
            	},
            },{
				name : "rooms",// "#",
				index : "rooms",
				width: 50,
			},{
				name : "arr_d",//"抵店",
				index : "arr_d",
				width: 100,
			},{
				name : "exp_dep_d",//"离店",
				index : "exp_dep_d",
				width : 100,
			},{
				name : "balance",//"余额",
				index : "balance",
				width : 120,
				align : "right",
			},{
				name : "pno",//"PNO",
				index : "pno",
				width : 120,
				hidden : true,
			},{
				name : "gno",//"GNO",
				index : "gno",
				width : 120,
				key : true,
				hidden : true,
			},{
				name : "grno",//"grno",
				index : "grno",
				width : 120,
				hidden : true,
			},{
				name : "party",//"party",
				index : "party",
				width : 120,
				hidden : true,
			}],    	
			scroll : true,
			sortname : "sortby",
			sortorder : "asc",
			viewrecords : true,
			multiselect : initDate.multiSelect,
			rowNum : 20,
			rowList : [10 , 20 , 30],
			pager : initDate.pager_selector,
			altRows : true, 
			shrinkToFit : false,
//			autoScroll : true,
//			scrollrows:true,
	        ondblClickRow: function(rowid) {
//	        	alert(JSON.stringify(param))
        		if(param.returnRoom!="yes"){
        			el.find("#serviceModalSelect").trigger("click")
        		}
        	}, 
        	onSelectRow:function(rowid){
	        },
			loadComplete : function(data) {
			
				var table = this;
				setTimeout(function(){
					updatePagerIcons(table);
					enableTooltips(table);
				}, 0);
				
//				var ids = jQuery(grid_selector).jqGrid('getDataIDs');
//				if(ids.length>0){
//					grid_selector.jqGrid('setSelection',ids[0]);
//				}
			}, 
			gridComplete: function (data) {//this对象为数据列表表格，所以找到数据内容表格和表头的容器后在查找ui-jqgrid-hdiv，表头容器
				//设置首行被选中
				
			},
			beforeProcessing:function(response){
				
			},
		});
		$(window).triggerHandler("resize.jqGrid"); 
	}
	
	/*
	 * 私有函数
	 * 刷新jqgrid
	 * 2016-06-01
	 */
	function jqGridFre(initDate,grid_selector,el,param){
		
		//构造表格数据
		var initc=jQuery.extend({}, initDate.where,initDate.fileds,initDate.table,initDate.wherestring);
		//刷新
		jQuery(grid_selector).jqGrid('setGridParam',{				
		   postData : $.HSAPI_ASKJSONINFO( JSON.stringify(initc),'RetrieveJqGridList',"{}",'listWithPage'),
		   url : initDate.url,
		   datatype : 'json',		
		   pager : initDate.pager_selector,
       }).trigger('reloadGrid');
	};
	
	/*
	 * 私有函数
	 * 翻页栏
	 * 
	 */
	function updatePagerIcons(table) {
		var replacement = {
				"ui-icon-seek-first" : "ace-icon fa fa-angle-double-left bigger-140",
				"ui-icon-seek-prev" : "ace-icon fa fa-angle-left bigger-140",
				"ui-icon-seek-next" : "ace-icon fa fa-angle-right bigger-140",
				"ui-icon-seek-end" : "ace-icon fa fa-angle-double-right bigger-140"
		};
		$(".ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon").each(function() {
			var icon = $(this);
			var $class = $.trim(icon.attr("class").replace("ui-icon", ""));

			if ($class in replacement)
				icon.attr("class", "ui-icon " + replacement[$class]);
		})
	};
	
	/*
	 * 私有函数
	 * 提示框
	 * 
	 */
	function enableTooltips(table) {
		$('.navtable .ui-pg-button').tooltip({	
			container : 'body'
		});
		$(table).find('.ui-pg-div').tooltip({
			container : 'body'
		});
	};
	
})(jQuery);